<script lang="ts" setup>
  import { ElMessage, FormInstance } from 'element-plus'
  import { nextTick, onMounted, reactive, ref } from 'vue'
  import { addDeptService, updateDeptService } from '@/api/dept'
  const listQuery = {
    url: '/department/getAll',
    params: {},
  }
  const ruleFormRef = ref()
  const dialogVisible = ref<boolean>(false)
  const title = ref('新增部门')
  const deptCascaderRef = ref()
  const isEdit = ref(false) // 标识是否为编辑模式
  const isCascaderDisabled = ref(false) // 控制级联选择器是否禁用
  let placeholder = ref<string>('')
  const emit = defineEmits(['refreshList'])
  onMounted(() => {
    // getDeptList() // 不再需要，组件内部会自动获取
  })
  const rules = reactive({
    name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
    // pid: [{ required: true, message: '请选择上级部门', trigger: 'change' }],
  })
  const ruleForm = ref({
    id: null, // 部门id,
    name: '',
    pid: null, // 上级部门id
    departmentLeader: '',
    desc: '',
    isUse: 1,
    instructorId: null, // 负责人id
  })
  //==============================BEGIN 功能函数====================================
  // 处理远程搜索组件传递回来的负责人id
  const handleInstructorChange = (id: string) => {
    ruleForm.value.instructorId = id
  }

  const handleDeptChange = (deptId: string | null, deptInfo: any) => {
    ruleForm.value.pid = deptId
    console.log('选中的部门id:', deptId)
  }
  const close = () => {
    ruleFormRef.value.resetFields()
  }
  const show = (item: any = {}) => {
    // 刷新部门级联选择器数据
    deptCascaderRef.value?.refresh()
    if (item.name) {
      // 编辑模式
      title.value = '编辑部门'
      isEdit.value = true
      nextTick(() => {
        Object.assign(ruleForm.value, item)
        // 判断是否为一级部门（没有上级部门或pid为null/undefined）
        const isTopLevel = !item.pid || item.pid === null || item.pid === undefined
        isCascaderDisabled.value = isTopLevel
        // 根据是否为一级部门设置不同的 placeholder
        placeholder.value = isTopLevel ? '当前为一级部门，无法修改上级部门' : '请选择上级部门'
        console.log('编辑部门 - 是否为一级部门:', isTopLevel, '部门pid:', item.pid)
      })
    } else {
      // 新增模式
      title.value = '新增部门'
      isEdit.value = false
      isCascaderDisabled.value = false
      placeholder.value = '若未选择父部门则默认为一级部门'
    }
    dialogVisible.value = true
  }
  // 确认按钮
  const handleConfim = async () => {
    await ruleFormRef.value.validate((valid, fields) => {
      if (valid) {
        dialogVisible.value = false
        if (title.value === '新增部门') {
          addDeptService(ruleForm.value).then(() => {
            ElMessage.success('新增部门成功')
            emit('refreshList')
          })
        } else {
          updateDeptService(ruleForm.value).then(() => {
            ElMessage.success('编辑部门成功')
            emit('refreshList')
          })
        }
      } else {
        console.log('提交错误!', fields)
      }
    })
  }
  //==================================END 功能函数===================================
  defineExpose({
    show,
  })
</script>
<template>
  <el-dialog v-model="dialogVisible" :title="title" width="40%" center @close="close">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px" status-icon>
      <el-form-item label="部门名称" prop="name">
        <el-input v-model.trim="ruleForm.name" clearable placeholder="请输入部门名称" />
      </el-form-item>
      <el-form-item label="上级部门" prop="pid">
        <Cascader
          ref="deptCascaderRef"
          v-model="ruleForm.pid"
          :list-query="listQuery"
          :disabled="isCascaderDisabled"
          :placeholder="placeholder"
          @select="handleDeptChange"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="departmentLeader">
        <RemoteSelect v-model="ruleForm.departmentLeader" placeholder="请输入名字进行模糊搜索" @select="handleInstructorChange" />
      </el-form-item>
      <el-form-item label="状态">
        <el-switch
          v-model="ruleForm.isUse"
          :active-value="1"
          :inactive-value="0"
          inline-prompt
          active-text="启用"
          inactive-text="禁用"
        ></el-switch>
      </el-form-item>
      <el-form-item label="备注" prop="desc">
        <el-input v-model="ruleForm.desc" type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer dialog-font">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfim">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped></style>
